package xyz.haijin.spider;

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;
import xyz.haijin.spider.dao.WallpaperTypeDao;
import xyz.haijin.spider.entity.WallpaperType;
import xyz.haijin.zt.mysql.core.BaseDAO;

/**
 * @Author liuhaijin
 * @Date 2022/3/29
 */
public class EnterDeskRepoPageProcessor implements PageProcessor {

    /**
     * 日志对象
     */
    private Logger logger  = LoggerFactory.getLogger(EnterDeskRepoPageProcessor.class);


    /**
     * 数据库对象
     */
    private BaseDAO baseDAO = new WallpaperTypeDao();

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000)
            //添加cookie之前一定要先设置主机地址，否则cookie信息不生效
            .setDomain("m.sj.enterdesk.com")
            //添加抓包获取的cookie信息
            .addCookie("r", "5281")
            .addCookie("t", "164d5bb4a51042605aa5507a6f65af27");
            //添加请求头，有些网站会根据请求头判断该请求是由浏览器发起还是由爬虫发起的
//            .addHeader("User-Agent",
//                    "ozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36 Core/1.47.516.400 QQBrowser/9.4.8188.400")
//            .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
//            .addHeader("Accept-Encoding", "gzip, deflate, sdch").addHeader("Accept-Language", "zh-CN,zh;q=0.8")
//            .addHeader("Connection", "keep-alive").addHeader("Referer", "https://m.sj.enterdesk.com/");

    @SneakyThrows
    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        Selectable selectable = html
                .xpath("/html/body/div[11]/div")
                .xpath("ul")
                .xpath("//li")
                ;
        for (Selectable node : selectable.nodes()) {
            Selectable selectableA = node.xpath("//a");
            String url = selectableA.xpath("/a/@href").toString();
            String name = selectableA.xpath("/a/text()").toString();
            WallpaperType wallpaperType = WallpaperType.builder().typeName(name).typeUrl(url).build();
            baseDAO.save(wallpaperType);
        }
        logger.info("html:"+selectable.toString());

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new EnterDeskRepoPageProcessor()).addUrl("https://m.sj.enterdesk.com/").thread(5).run();
    }
}
